package com.azxc.rapid.auth.granter;

import com.azxc.rapid.auth.constant.AuthConstant;
import com.azxc.rapid.auth.jianguan.SuperviseAuthenticationToken;
import com.azxc.rapid.auth.service.RapidUserDetails;
import com.azxc.rapid.auth.utils.TokenUtil;
import com.azxc.rapid.core.redis.cache.RapidRedis;
import com.azxc.rapid.core.tool.api.R;
import com.azxc.rapid.core.tool.support.Kv;
import com.azxc.rapid.core.tool.utils.Func;
import com.azxc.rapid.core.tool.utils.WebUtil;
import com.azxc.rapid.supervise.feign.ISuperviseClient;
import com.azxc.rapid.system.user.entity.User;
import com.azxc.rapid.system.user.entity.UserInfo;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 验证码TokenGranter
 */
public class SuperviseTokenGranter extends AbstractTokenGranter {

	private static final String GRANT_TYPE = "supervise";

	private final AuthenticationManager authenticationManager;

	private RapidRedis rapidRedis;

	private ISuperviseClient superviseClient;

	public SuperviseTokenGranter(AuthenticationManager authenticationManager,
								 AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, RapidRedis rapidRedis,ISuperviseClient superviseClient) {
		this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
		this.rapidRedis = rapidRedis;
		this.superviseClient=superviseClient;
	}

	protected SuperviseTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
									ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
		super(tokenServices, clientDetailsService, requestFactory, grantType);
		this.authenticationManager = authenticationManager;
	}

	@Override
	protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
		HttpServletRequest request = WebUtil.getRequest();


		Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
		String username = parameters.get("tele");
		String tenantId = Func.toStr(request.getHeader(TokenUtil.TENANT_HEADER_KEY), TokenUtil.DEFAULT_TENANT_ID);

		RapidUserDetails rapidUserDetails;
		R<UserInfo> result= superviseClient.userInfo(username);
		if (result.isSuccess()) {
			User user = result.getData().getUser();
			Kv detail = result.getData().getDetail();
			if (user == null) {
				throw new InvalidGrantException("supervise grant failure, user is null");
			}
			rapidUserDetails = new RapidUserDetails(user.getId(),
				tenantId, result.getData().getOauthId(), user.getName(), user.getRealName(), user.getDeptId(), user.getPostId(), user.getRoleId(), Func.join(result.getData().getRoles()),null,
				user.getName(), AuthConstant.ENCRYPT + user.getPassword(), detail, true, true, true, true,
				AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(result.getData().getRoles())));
		} else {
			throw new InvalidGrantException("supervise grant failure, feign client return error");
		}


		Authentication userAuth = new SuperviseAuthenticationToken(username,AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(result.getData().getRoles())));
		((AbstractAuthenticationToken) userAuth).setDetails(parameters);
		userAuth = authenticationManager.authenticate(userAuth);


		// If the username/password are wrong the spec says we should send 400/invalid grant
		if (userAuth == null || !userAuth.isAuthenticated()) {
			throw new InvalidGrantException("Could not authenticate user: " + username);
		}
		((AbstractAuthenticationToken) userAuth).setDetails(rapidUserDetails);
		OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
		return new OAuth2Authentication(storedOAuth2Request, userAuth);
	}
}
